package com.wanshi.test;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;

import java.io.*;

public class BB {

    public static void main(String[] args) throws FileNotFoundException {

        String endpoint = "oss-cn-beijing.aliyuncs.com";//oss-cn-shanghai.aliyuncs.com
        String accessKeyId = "LTAI5tGY2S8bmneQ6b3J1ip4";//你的keyid
        String accessKeySecret = "9zLRxX5h3KzfgAuo54eqlullPPBtNr";//你的keysecret
        String bucketName = "caochengyu";//bucket名称

        String fileUrl = "http://caochengyu.oss-cn-beijing.aliyuncs.com/settle/2021/12/16/21F9BEAA98F0CE85D43794BC70CB1BFF.pdf";

        String folder = fileUrl;
        int index = fileUrl.lastIndexOf("/");
        String fileName = fileUrl.substring(index+1,fileUrl.length());
        BufferedInputStream input = null;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, folder);

        FileOutputStream outputStream = new FileOutputStream("");
        try {


            input = new BufferedInputStream(ossObject.getObjectContent());
            byte[] buffBytes = new byte[1024];
            int read = 0;
            while ((read = input.read(buffBytes)) != -1) {
                outputStream.write(buffBytes, 0, read);
            }
            outputStream.flush();
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ossClient.shutdown();
    }
}
